<?php
/**
 * 设置菜单权限
 * User：liujun
 * Date：2022/3/5
 * Time：11:16 AM
 */

namespace Encore\Admin\Actions\Custom;

use DB;
use Encore\Admin\Actions\Action;
use Encore\Admin\Actions\Response;

class MenuSetPermissionAction extends Action
{
    use AutoMatchAdminMenuTrait;

    protected $selector = '.menu-set-permission-action';
    public $name = '设置菜单权限';

    public function handle(): Response
    {
        $menuTable = config('admin.database.menu_table');
        $permissionTable = config('admin.database.permissions_table');

        $menus = DB::table($menuTable)->whereNotNull('uri')->get(['id', 'title', 'uri', 'permission']);

        //将菜单uri数据转换为权限slug样式
        $slugs = $menus->map(function ($item) {
            return \Illuminate\Support\Str::replace('-', '_', $item->uri) . '.view';
        })->toArray();

        $slugs = DB::table($permissionTable)->whereIn('slug', $slugs)->pluck('slug')->toArray();

        //get id by slug from slugIds
        $menus->map(function ($item) use ($slugs,$menuTable) {
            $uri = \Illuminate\Support\Str::replace('-', '_', $item->uri) . '.view';
            if (in_array($uri, $slugs)) {
                DB::table($menuTable)->where('id', $item->id)->update(['permission' => $uri]);
            }
        });
        return $this->response()->success('菜单权限设置成功')->refresh();
    }

    public function dialog()
    {
        $this->confirm('确定设置菜单权限吗？');
    }

    public function html(): string
    {
        return '<a href="javascript:;" class="btn btn-sm bg-navy menu-set-permission-action"><i class="fa fa-cog"></i><span class="hidden-xs"> 设置权限</span></a>';
    }
}